//
//  SEGLogoutViewController.m
//  SEGStandard
//
//  Created by 乔杨 on 2020/7/27.
//

#import "SEGLogoutViewController.h"

#import <Commom/UITextField+Limit.h>
#import <Commom/SEGSafaKeyboard.h>
#import <Commom/SEGPasswordTextField.h>

#import <SEGViewModel/SEGLogoutViewModel.h>

static CGFloat const kCell_H = 44.f;

@interface SEGLogoutViewController ()<UITextFieldDelegate, SGETextFieldLimitDelegate, SEGNewAlertViewDelegate>

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIView *line1View;
@property (nonatomic, strong) UIView *line2View;
/// 手机号
@property (nonatomic, strong) UILabel *phoneLab;
/// 图片验证码
@property (nonatomic, strong) UITextField *checkImgTF;
@property (nonatomic, strong) UIImageView *checkImgView;
@property (nonatomic, strong) UIButton *freshCheckImgBtn;
/// 短信验证码
@property (nonatomic, strong) UITextField *checkSmsTF;
@property (nonatomic, strong) UIButton *getSmsButton;
/// 语音验证码
@property (nonatomic, strong) UILabel *getSoundMsgLabel;
@property (nonatomic, strong) UIButton *getSoundMsgButton;

/// 导航栏右侧确定按钮
@property (nonatomic, strong) UIButton *confirmButton;
/// 定时器取消
@property (nonatomic, strong) RACDisposable *disposable;
/// viewModel
@property (nonatomic, strong) SEGLogoutViewModel *viewModel;

@end

@implementation SEGLogoutViewController

- (void)dealloc {
    [self.disposable dispose];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kColor_bg;
    self.title = @"注销账号";
    [self showCustomNavigationBackButton];
    self.confirmButton = [self showCustomNavigationRightButtonWithColorTitle:@"确定" titleColor:kColor_T disabledColor:kColor_C];
    self.confirmButton.enabled = NO;
    
    [self setupUI];
    
    // 刷新图片验证码
    [self freshCheckImgForgetPassword];
    // 绑定信号
    [self seg_bindSignal];
}

#pragma mark - Bind
- (void)seg_bindSignal {
    RACChannelTo(self.viewModel, checkImgStr) = self.checkImgTF.rac_newTextChannel;
    RACChannelTo(self.viewModel, smsCodeStr) = self.checkSmsTF.rac_newTextChannel;
}

#pragma mark - Event
// 刷新图片验证码
- (void)freshCheckImgForgetPassword {
    @weakify(self);
    [self.viewModel.refreshImgSignal subscribeNext:^(UIImage *decodedImage) {
        @strongify(self);
        if (decodedImage) {
            [self.checkImgView setImage:decodedImage];
        } else {
            [self.checkImgView setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_72_72")]];
        }
        // 确定按钮高亮状态
        [self updateSubmitButtonStatus];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
        // 确定按钮高亮状态
        [self updateSubmitButtonStatus];
    }];
}
// 发送验证码
- (void)getSMSmessage {
    @weakify(self);
    [self.viewModel.captchasSignal subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [SEGAlertView showTmepMessageWithMessage:@"验证码已发送"];
        [self sentPhoneCodeTimeMethod];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
        if (error.code == 1) {
            // 刷新图形验证码
            [self freshCheckImgForgetPassword];
        }
    }];
}
// 计时器发送验证码
- (void)sentPhoneCodeTimeMethod {
    // 倒计时时间 —— 60秒
    __block NSInteger timeOut = 59;
    @weakify(self);
    self.disposable = [[RACSignal interval:1 onScheduler:[RACScheduler mainThreadScheduler]] subscribeNext:^(NSDate * _Nullable x) {
        @strongify(self);
        if (timeOut < 0) {
            [self.disposable dispose];
            [self.getSmsButton setTitle:kRefreshGetMessageCodeTitle forState:UIControlStateNormal];
            self.getSmsButton.enabled = YES;
            self.getSoundMsgButton.enabled = YES;
        } else {
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDuration:1.0];
            [self.getSmsButton setTitle:[NSString stringWithFormat:@"%ldS", timeOut] forState:UIControlStateNormal];
            self.getSmsButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
            [UIView commitAnimations];
            // 计时器件不允许点击
            self.getSmsButton.enabled = NO;
            self.getSoundMsgButton.enabled = NO;
            timeOut --;
        }
    }];
}
// 获取语音验证码
- (void)getSoundMessage {
    @weakify(self);
    [self.viewModel.soundCodeSignal subscribeNext:^(NSString *message) {
        @strongify(self);
        [SEGAlertView showTmepMessageWithMessage:@"验证码已发送"];
        [self sentPhoneCodeTimeMethod];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
        // 语音验证码失败清空&刷新图形验证码
        if (error.code == 1) {
            [self freshCheckImgForgetPassword];
        }
    }];
}
// 导航栏上，“确定”按钮触发方法 (注销账号)
- (void)onNavigationRightButtonClicked:(UIButton *)sender {
    [self.view endEditing:YES];
    SEGNewAlertView *alert = [[SEGNewAlertView alloc] init];
    [alert showWithAlertText:@"你是否确定注销账号？注销后账号无法再使用。" delegate:self buttonTitlesArray:@[@"取消", @"注销"]];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark - SEGNewAlertViewDelegate
- (void)segNewAlertView:(UIView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        // 注销账号
        [self.viewModel.sureBtnSignal subscribeNext:^(NSString *message) {
            [SEGAlertView showTmepMessageWithMessage:message withtime:1.5];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                // 清除账号密码, 退到登录界面
                [SEGLoginV2Manager segSaveUserTelToLocal:@""];
                [SEGLoginV2Manager segSaveUserPasswordToLocal:@""];
                [[SEGUhomeMediator sharedInstance] seg_pushToLoginViewController:nil];
            });
        } error:^(NSError * _Nullable error) {
            [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
            // 确定按钮高亮状态
            [self updateSubmitButtonStatus];
        }];
    } 
}

#pragma mark - UITextFieldDelegate 键盘隐藏
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField {
    return YES;
}
#pragma mark - SGETextFieldLimitDelegate
- (void)limitTextFileDidChange:(UITextField *)textField {
    [self updateSubmitButtonStatus];
}
- (void)updateSubmitButtonStatus {
    if (self.phoneLab.text.length > 0 && self.checkSmsTF.text.length > 0 && self.checkImgTF.text.length > 0) {
        self.confirmButton.enabled = YES;
    }  else {
        self.confirmButton.enabled = NO;
    }
}
 
#pragma mark - UI
- (void)setupUI {
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.mas_equalTo(0);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(kCell_H * 3);
    }];
    
    [self.view addSubview:self.line1View];
    [self.line1View mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.bottomView).mas_offset(kCell_H-0.5);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(0.5);
    }];

    [self.view addSubview:self.line2View];
    [self.line2View mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.bottomView).mas_offset(2*kCell_H-0.5);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(0.5);
    }];

    [self.view addSubview:self.phoneLab];
    [self.phoneLab mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.bottomView);
        make.height.mas_equalTo(kCell_H);
        make.left.equalTo(self.bottomView).mas_offset(15);
        make.right.equalTo(self.bottomView).mas_offset(-15);
    }];
    
    // 图形验证码 输入
    [self.view addSubview:self.checkImgTF];
    [self.checkImgTF mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.line1View.mas_bottom);
        make.left.equalTo(self.bottomView).mas_offset(15);
        make.right.equalTo(self.bottomView.mas_right).mas_offset(-129);
        make.height.mas_equalTo(kCell_H);
    }];
    
    [self.freshCheckImgBtn sizeToFit];
    
    // 图形验证码 图片
    [self.view addSubview:self.checkImgView];
    [self.checkImgView mas_makeConstraints:^(MASConstraintMaker* make) {
        make.right.equalTo(self.bottomView.mas_right).mas_offset(-(25 + self.freshCheckImgBtn.bounds.size.width));
        make.width.mas_equalTo(65);
        make.height.mas_equalTo(27);
        make.centerY.equalTo(self.checkImgTF);
    }];
    // 刷新按钮
    UIButton *refreshBtn = [[UIButton alloc] init];
    [refreshBtn addTarget:self action:@selector(freshCheckImgForgetPassword) forControlEvents:UIControlEventTouchUpInside];
    [self.checkImgView addSubview:refreshBtn];
    [refreshBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.checkImgView);
    }];

    
    // 图形验证码 "换一张"
    [self.view addSubview:self.freshCheckImgBtn];
    [self.freshCheckImgBtn mas_makeConstraints:^(MASConstraintMaker* make) {
        make.right.equalTo(self.bottomView.mas_right).mas_offset(-15);
        make.centerY.equalTo(self.checkImgView);
    }];

    // 短信验证码 输入
    [self.view addSubview:self.checkSmsTF];
    [self.checkSmsTF mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.line2View.mas_bottom);
        make.height.mas_equalTo(kCell_H);
        make.left.equalTo(self.bottomView).mas_offset(15);
        make.width.mas_equalTo(self.line2View).mas_offset(-105);
    }];
 
    [self.view addSubview:self.getSmsButton];
    [self.getSmsButton mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.line2View.mas_bottom);
        make.bottom.equalTo(self.bottomView.mas_bottom);
        make.right.equalTo(self.view).mas_offset(-15);
    }];

    // 语音验证码
    [self.view addSubview:self.getSoundMsgButton];
    [self.getSoundMsgButton mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.bottomView.mas_bottom).mas_offset(11);
        make.right.equalTo(self.bottomView.mas_right).mas_offset(-15);
        make.width.mas_greaterThanOrEqualTo(kCell_H);
        make.height.mas_equalTo(15);
    }];
    [self.view addSubview:self.getSoundMsgLabel];
    [self.getSoundMsgLabel mas_makeConstraints:^(MASConstraintMaker* make) {
        make.centerY.equalTo(self.getSoundMsgButton.mas_centerY);
        make.right.equalTo(self.getSoundMsgButton.mas_left);
        make.width.mas_greaterThanOrEqualTo(kCell_H);
        make.height.equalTo(self.getSoundMsgButton.mas_height);
    }];
 
}

#pragma mark - Getter
// 手机号码，图片验证码，手机验证码的白色背景框
- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
        _bottomView.backgroundColor = kColor_W;
    }
    return _bottomView;
}
- (UIView *)line1View {
    if (!_line1View) {
        _line1View = [[UIView alloc] init];
        _line1View.backgroundColor = kColor_L2;
    }
    return _line1View;
}
- (UIView *)line2View {
    if (!_line2View) {
        _line2View = [[UIView alloc] init];
        _line2View.backgroundColor = kColor_L2;
    }
    return _line2View;
}
// 手机号
- (UILabel *)phoneLab {
    if (!_phoneLab) {
        _phoneLab = [[UILabel alloc] init];
        _phoneLab.textColor = kColor_1;
        _phoneLab.font = kFont_16;
        NSString *phoneStr = [NSString stringWithFormat:@"%@（当前账号）",kAccountMobile];
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:phoneStr];
        [attributedString addAttribute:NSForegroundColorAttributeName value:kColor_3 range:NSMakeRange(kAccountMobile.length, phoneStr.length-kAccountMobile.length)];
        [_phoneLab setAttributedText:attributedString];
    }
    return _phoneLab;
}
// 图片验证码
- (UITextField *)checkImgTF {
    if (!_checkImgTF) {
        _checkImgTF = [[UITextField alloc] init];
        [_checkImgTF setTextColor:kColor_1];
        [_checkImgTF setTintColor:kColor_T];
        _checkImgTF.font = kFont_16;
        [_checkImgTF setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"图片验证码" attributes:@{NSForegroundColorAttributeName:kColor_C}]];
        _checkImgTF.clearsOnBeginEditing = NO;
        _checkImgTF.delegate = self;
        _checkImgTF.clearButtonMode = UITextFieldViewModeNever;
        [_checkImgTF setKeyboardType:UIKeyboardTypeWebSearch];
        [_checkImgTF configImgCodeInputLimitWithDelegate:self];
    }
    return _checkImgTF;
}
- (UIImageView *)checkImgView {
    if (!_checkImgView) {
        _checkImgView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_72_72")]];
        [_checkImgView setUserInteractionEnabled:YES];
    }
    return _checkImgView;
}
- (UIButton *)freshCheckImgBtn {
    if (!_freshCheckImgBtn) {
        _freshCheckImgBtn = [[UIButton alloc] init];
        [_freshCheckImgBtn setTitle:@"换一张" forState:UIControlStateNormal];
        [_freshCheckImgBtn.titleLabel setFont:kFont_16];
        [_freshCheckImgBtn setTitleColor:kColor_T forState:UIControlStateNormal];
        _freshCheckImgBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        [_freshCheckImgBtn addTarget:self action:@selector(freshCheckImgForgetPassword) forControlEvents:UIControlEventTouchUpInside];
    }
    return _freshCheckImgBtn;
}
// 短信验证码
- (UITextField *)checkSmsTF {
    if (!_checkSmsTF) {
        _checkSmsTF = [[UITextField alloc] init];
        [_checkSmsTF setTextColor:kColor_1];
        [_checkSmsTF setTintColor:kColor_T];
        [_checkSmsTF setFont:kFont_16];
        [_checkSmsTF setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"手机验证码" attributes:@{NSForegroundColorAttributeName:kColor_C}]];
        _checkSmsTF.clearsOnBeginEditing = NO;
        _checkSmsTF.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        _checkSmsTF.delegate = self;
        _checkSmsTF.keyboardType = UIKeyboardTypeNumberPad;
        [_checkSmsTF configSMSCodeInputLimitWithDelegate:self];
    }
    return _checkSmsTF;
}
- (UIButton *)getSmsButton {
    if (!_getSmsButton) {
        _getSmsButton = [[UIButton alloc] init];
        [_getSmsButton setTitle:kGetMessageCodeTitle forState:UIControlStateNormal];
        _getSmsButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        _getSmsButton.titleLabel.font = kFont_16;
        [_getSmsButton setTitleColor:kColor_T forState:UIControlStateNormal];
        [_getSmsButton setTitleColor:kColor_3 forState:UIControlStateDisabled];
        [_getSmsButton addTarget:self action:@selector(getSMSmessage) forControlEvents:UIControlEventTouchUpInside];
    }
    return _getSmsButton;
}
- (UILabel *)getSoundMsgLabel {
    if (!_getSoundMsgLabel) {
        _getSoundMsgLabel = [[UILabel alloc] init];
        _getSoundMsgLabel.textColor = kColor_3;
        _getSoundMsgLabel.font = kFont_11;
        _getSoundMsgLabel.text = @"收不到验证码？试试";
    }
    return _getSoundMsgLabel;
}
- (UIButton *)getSoundMsgButton {
    if (!_getSoundMsgButton) {
        _getSoundMsgButton = [[UIButton alloc] init];
        [_getSoundMsgButton setTitle:@"语音验证码" forState:UIControlStateNormal];
        UIColor *normalColor = kColor_S3;
        [_getSoundMsgButton setTitleColor:normalColor forState:UIControlStateNormal];
        [_getSoundMsgButton setTitleColor:kColor_3 forState:UIControlStateDisabled];
        _getSoundMsgButton.titleLabel.font = kFont_11;
        [_getSoundMsgButton addTarget:self action:@selector(getSoundMessage) forControlEvents:UIControlEventTouchUpInside];
    }
    return _getSoundMsgButton;
}
- (SEGLogoutViewModel *)viewModel {
    if (!_viewModel) _viewModel = [SEGLogoutViewModel new];
    return _viewModel;
}

@end
